package taskprocess

import (
	"acs/comet/client"
	"acs/comet/proto"
	"acs/pbmodel"
)

// HandleSchemaUpdate 保存schema信息，并根据schema信息向在线客户端推送patch通知。
func HandleSchemaUpdate(task *SchemaTask) (err error) {
	err = StoreTaskToDb(task)
	if err != nil {
		logger.Warnf("Failed to handle schema update task. ERR: %v", err)
		return
	}
	upFn := func(c *client.Client, taskI interface{}) {
		task := taskI.(*SchemaTask)
		regInfo := c.GetRegisterInfo()
		if *regInfo.BundleID != task.BundleID || (task.PrevSchemaID != "*" && *regInfo.LSID != task.PrevSchemaID) || AppPlatform(*regInfo.System) != task.Platform {
			return
		}
		var isTargetClient bool
		for _, uid := range task.TargetUID {
			if uid == *regInfo.UID {
				isTargetClient = true
			}
		}
		if !isTargetClient {
			return
		}
		logger.Debugf("Sending schema update task to user[%v]: %+v", regInfo.UID, *task)
		resp := c.SendCmd(proto.CmdSchema, &task.Schema, &pbmodel.SchemaResp{})

		if resp.Err != nil {
			logger.Warnf("Schema update failed to [%v]: %v", c.GetRemoteAddr(), resp.Err)
			return
		}
		respData := resp.RespData.(*pbmodel.SchemaResp)
		if *respData.Status != 0 {
			logger.Warnf("Client[%v] schema update failed: %v:%v", c.GetRemoteAddr(), respData.Status, respData.Msg)
		}
	}
	clients.MapFunc(upFn, task)
	return
}
